package com.sansecy.leanbacktest.list;

import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.leanback.widget.VerticalGridView;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.sansecy.leanbacktest.R;

import java.util.ArrayList;
import java.util.Random;

public class ListFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list, container, false);
        VerticalGridView VerticalGridView = view.findViewById(R.id.VerticalGridView);
        VerticalGridView.setNumColumns(3);
        final ArrayList<String> strings = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < 1000; i++) {
            strings.add(String.valueOf(random.nextInt()));
        }
        ListAdapter<String, MyHolder> adapter = new ListAdapter<String, MyHolder>(new DiffUtil.ItemCallback<String>() {

            @Override
            public boolean areItemsTheSame(@NonNull String oldItem, @NonNull String newItem) {
                return oldItem.equals(newItem);
            }

            @Override
            public boolean areContentsTheSame(@NonNull String oldItem, @NonNull String newItem) {
                return oldItem.equals(newItem);
            }

        }) {
            @NonNull
            @Override
            public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_view, parent, false);
                return new MyHolder(view1);
            }

            @Override
            public void onBindViewHolder(@NonNull MyHolder holder, int position) {
                String item = getItem(position);
                holder.textView.setText(item);
            }
        };
        VerticalGridView.setAdapter(adapter);
        adapter.submitList(strings);
        return view;
    }

    static class MyHolder extends RecyclerView.ViewHolder {
        TextView textView;

        public MyHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.textView);
            textView.setGravity(Gravity.CENTER);
            textView.setTextColor(Color.WHITE);
            textView.setBackgroundResource(R.drawable.card_selector);
        }
    }

}
